package com.example.musicwebcon.service;

import com.example.musicwebcon.model.dto.playingListDTO;
import com.example.musicwebcon.model.playingList;
import com.example.musicwebcon.repository.playingRepository;
import com.example.musicwebcon.service.serviceInterface.IplayingService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class playingService implements IplayingService {
    @Autowired
    playingRepository playingRepository;

    @Override
    public playingList add(playingListDTO playingListSong) {
        playingList song = new playingList();
        BeanUtils.copyProperties(playingListSong,song);
        song.setCreatTime(LocalDateTime.now().plusNanos(System.nanoTime() % 1000));
        return playingRepository.save(song);
    }

    @Override
    public Iterable<playingList> addBatch(Iterable<playingListDTO> playingListSongs) {
        Iterable<playingList> playingLists = new ArrayList<>();
        for (playingListDTO dto: playingListSongs){
            playingList song = new playingList();
            BeanUtils.copyProperties(dto,song);
            song.setCreatTime(LocalDateTime.now().plusNanos(System.nanoTime() % 1000));
            ((List<playingList>)playingLists).add(song);
        }
        return playingRepository.saveAll(playingLists);
    }

    @Override
    public playingList getMusicId(String musicId) {
        return playingRepository.findById(musicId).orElseThrow(() -> {
            throw new IllegalArgumentException("歌曲不存在，参数异常！");
        });
    }

    @Override
    public Iterable<playingList> getALl() {
        return playingRepository.findAllByOrderByCreatTimeDesc();
    }

    @Override
    public Iterable<playingList> getALl2() {
        return playingRepository.findAll();
    }

    @Override
    public Iterable<playingList> getALlBysongIndex() {
        return playingRepository.findAllByOrderBySongIndexAsc();
    }

    @Override
    public playingList edit(playingListDTO playingListSong) {
        playingList song = new playingList();
        BeanUtils.copyProperties(playingListSong,song);
        return playingRepository.save(song);
    }

    @Override
    public void deleteMusicId(String musicId) {
        playingRepository.deleteById(musicId);
    }

    @Override
    public void deleteAll() {
        playingRepository.deleteAll();
    }
}
